<template>
  <div class="calendar">
    <div class="calendar-header">
      <button @click="prevMonth">上一月</button>
      <span>{{ currentYear }}年 {{ currentMonth + 1 }}月</span>
      <button @click="nextMonth">下一月</button>
    </div>
    <div class="calendar-body">
      <div class="weekdays">
        <div v-for="day in weekdays" :key="day" class="weekday">{{ day }}</div>
      </div>
      <div class="days">
        <div v-for="(day, index) in days" :key="index" class="day" :class="{ 'other-month': !day.isCurrentMonth }">
          {{ day.date }}
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue';

const currentDate = ref(new Date());
const weekdays = ['日', '一', '二', '三', '四', '五', '六'];

const currentYear = computed(() => currentDate.value.getFullYear());
const currentMonth = computed(() => currentDate.value.getMonth());

const days = computed(() => {
  const year = currentYear.value;
  const month = currentMonth.value;
  const firstDayOfMonth = new Date(year, month, 1);
  const lastDayOfMonth = new Date(year, month + 1, 0);
  const daysInMonth = lastDayOfMonth.getDate();
  const startDay = firstDayOfMonth.getDay();

  const daysArray = [];

  for (let i = startDay; i > 0; i--) {
    const date = new Date(year, month, -i + 1);
    daysArray.push({ date: date.getDate(), isCurrentMonth: false });
  }

  for (let i = 1; i <= daysInMonth; i++) {
    daysArray.push({ date: i, isCurrentMonth: true });
  }

  const endDay = lastDayOfMonth.getDay();
  for (let i = 1; i < 7 - endDay; i++) {
    const date = new Date(year, month + 1, i);
    daysArray.push({ date: date.getDate(), isCurrentMonth: false });
  }

  return daysArray;
});

const prevMonth = () => {
  currentDate.value = new Date(currentYear.value, currentMonth.value - 1, 1);
};

const nextMonth = () => {
  currentDate.value = new Date(currentYear.value, currentMonth.value + 1, 1);
};
</script>

<style scoped>
.calendar {
  width: 300px;
  font-family: Arial, sans-serif;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.calendar-header button {
  background: none;
  border: 1px solid #ccc;
  padding: 5px 10px;
  cursor: pointer;
}

.calendar-body {
  display: grid;
  grid-template-rows: auto 1fr;
}

.weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  font-weight: bold;
}

.days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 5px;
}

.day {
  text-align: center;
  padding: 10px;
  border: 1px solid #ccc;
}

.other-month {
  color: #ccc;
}
</style>